﻿using System;
using System.Windows.Forms;
using JUtil.WinForm.Extensions;
using JUtil.Extensions;

partial class OleDbConnectionStringEditor : UserControl
{
    enum Provider
    {
        Odbc,
        Oracle,
        SqlServer
    }

    public OleDbConnectionStringEditor()
    {
        InitializeComponent();

        cbProvider.InitComboBox<Provider>();

        cbProvider.SetValue(default(Provider));
    }

    public OleDbConnectionStringEditor(string connectionString)
    {
        InitializeComponent();

        cbProvider.InitComboBox<Provider>();

        OleDbConnectionStringBuilder builder = new OleDbConnectionStringBuilder(connectionString);

        switch(builder.Provider)
        {
            case "MSDASQL.1":
                {
                    cbProvider.SetValue(Provider.Odbc);
                }
                break;

            case "MSDAORA.1":
                {
                    cbProvider.SetValue(Provider.Oracle);
                }
                break;

            case "SQLOLEDB.1":
                {
                    cbProvider.SetValue(Provider.SqlServer);
                }
                break;
        }

        tbPwd.Text = builder.Password;
        tbUid.Text = builder.ID;
        tbDatabase.Text = builder.Catalog;
        tbServer.Text = builder.Source;
    }

    public override string ToString()
    {
        Provider provider = cbProvider.GetValue<Provider>();

        switch (provider)
        {
            case Provider.Odbc:
                return string.Format("Provider=MSDASQL.1;Password={0};Persist Security Info=True;User ID={1};Data Source={2}", tbPwd.Text, tbUid.Text, tbServer.Text);
            case Provider.Oracle:
                return string.Format("Provider=MSDAORA.1;Password={0};User ID={1};Data Source={2};Persist Security Info=True", tbPwd.Text, tbUid.Text, tbServer.Text);
            case Provider.SqlServer:
                return string.Format("Provider=SQLOLEDB.1;Password={0};Persist Security Info=True;User ID={1};Initial Catalog={2};Data Source={3}", tbPwd.Text, tbUid.Text, tbDatabase.Text, tbServer.Text);
            default:
                throw new ArgumentOutOfRangeException("provider");
        }
    }

    private void cbProvider_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        Provider provider = cbProvider.GetValue<Provider>();

        bool show = (Provider.SqlServer == provider);

        lbDatabase.Visible = show;
        tbDatabase.Visible = show;
    }
}
